package com.young.ysepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.young.ysepay.dao.YsWithdrawalReceiptDao;
import com.young.ysepay.domain.YsWithdrawalReceiptDO;
import com.young.ysepay.dto.YsPayDTO;
import com.young.ysepay.service.*;
import com.young.ysepay.utils.DateFormatHelper;
import com.young.ysepay.utils.Https;
import com.young.ysepay.utils.JSONUtils;
import com.young.ysepay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: WANGNING
 * @Email wyn20140226@aliyun.com
 * @Date: 2019/6/4 18:42
 * @Des 银盛一清提现业务处理
 */
@Service
public class YsWithdrawalServiceImpl implements YsWithdrawalService {
    @Autowired
    private YsBusinessPramService ysBusinessPramService;
    @Autowired
    private YsBuildRequestParaService ysBuildRequestParaService;
    @Autowired
    private YsVerifyJsonSignService ysVerifyJsonSignService;
    @Autowired
    private YsWithdrawalReceiptService ysWithdrawalReceiptService;
    private static Logger log = LoggerFactory.getLogger(YsWithdrawalServiceImpl.class);
    @Override
    public String withdrawal(Map<String, Object> mapParams) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        YsPayDTO ysPayDTO=ysBusinessPramService.ysBusinessPram();
        Object temp = mapParams.get("biz_content");
        String bizContent = temp != null ? temp.toString() : null;
        String str = "";
        //封装公共请求参数Map
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("method", "ysepay.merchant.withdraw.quick.accept");
        paramMap.put("partner_id", ysPayDTO.getPARTNER_ID());
        paramMap.put("timestamp", DateFormatHelper.getNowTimeStr());
        paramMap.put("charset", ysPayDTO.getDEFAULT_CHARSET());
        paramMap.put("sign_type", ysPayDTO.getSIGN_ALGORITHM());
        paramMap.put("version", ysPayDTO.getVERSION());
        paramMap.put("notify_url", ysPayDTO.getNOTIFY_WITHDRAWAL_URL());
        paramMap.put("biz_content", bizContent);

        //签名信息
        try {
            Map<String, String> sParaMap = ysBuildRequestParaService.buildRequestPara(paramMap);
            String returns = Https.httpsSend(ysPayDTO.getYSEPAY_GATEWAY_URL_DSF(), sParaMap);
            resultMap = (Map) JSON.parse(returns);
            Object obj = resultMap.get("ysepay_merchant_withdraw_quick_accept_response");
            boolean verifyResult = false;
            if (obj != null) {
                //Map<String, Object> ysepay_response = (Map) JSON.parseObject(obj.toString());
                int yscount = returns.toString().indexOf("ysepay_merchant_withdraw_quick_accept_response");
                str = returns.substring(yscount);
                str = str.replace("ysepay_merchant_withdraw_quick_accept_response", "");
                str = str.substring(2, str.length() - 1);
                verifyResult = ysVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), str, "utf-8");
                log.error("验证签名是否成功"+verifyResult);
                log.error("提现返回信息"+str);
                //提现同步回执日志记录
                //saveSyncWithdrawal(str);
                return str;

            }
        } catch (IOException e) {
            log.error("银盛一清提现请求失败"+e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e1) {
            log.error("银盛一清提现请求失败"+e1.getMessage());
            e1.printStackTrace();
        } finally {
            return str;
        }
    }

    private void saveSyncWithdrawal(String str) {
        YsWithdrawalReceiptDO ysWithdrawalReceiptDO = new YsWithdrawalReceiptDO();
        Map<String, Object> map = JSONUtils.jsonToMap(str);
        try {
            if(map.get("code").toString() != null && map.get("code").toString().equals("10000")){
                String out_trade_no = map.get("out_trade_no").toString();
                String trade_status = map.get("trade_status").toString();
                String trade_status_description = map.get("trade_status_description").toString();
                String total_amount = map.get("total_amount").toString();
                String account_date = map.get("account_date").toString();
                String trade_no = map.get("trade_no").toString();
                String fee = map.get("fee").toString();
                String partner_fee = map.get("partner_fee").toString();
                String payee_fee = map.get("payee_fee").toString();
                String payer_fee = map.get("payer_fee").toString();
                ysWithdrawalReceiptDO.setAccountDate(account_date);
                ysWithdrawalReceiptDO.setFee(new BigDecimal(fee));
                ysWithdrawalReceiptDO.setGmtCreate(new Date());
                ysWithdrawalReceiptDO.setGmtModified(new Date());
                ysWithdrawalReceiptDO.setIsDelete("1");
                ysWithdrawalReceiptDO.setOutTradeNo(out_trade_no);
                ysWithdrawalReceiptDO.setTradeStatus(trade_status);
                ysWithdrawalReceiptDO.setTotalAmount(new BigDecimal(total_amount));
                ysWithdrawalReceiptDO.setResponseType("1");
                ysWithdrawalReceiptDO.setPartnerFee(new BigDecimal(partner_fee));
                ysWithdrawalReceiptDO.setPayeeFee(new BigDecimal(payee_fee));
                ysWithdrawalReceiptDO.setPayerFee(new BigDecimal(payer_fee));
                ysWithdrawalReceiptDO.setTradeNo(trade_no);
                ysWithdrawalReceiptDO.setTradeStatusDescription(trade_status_description);
                ysWithdrawalReceiptService.save(ysWithdrawalReceiptDO);
            }else {
                String out_trade_no = map.get("out_trade_no").toString();
                ysWithdrawalReceiptDO.setOutTradeNo(out_trade_no);
                ysWithdrawalReceiptDO.setResponseType("1");
                ysWithdrawalReceiptDO.setIsDelete("1");
                ysWithdrawalReceiptDO.setGmtModified(new Date());
                ysWithdrawalReceiptDO.setGmtCreate(new Date());
                ysWithdrawalReceiptDO.setTradeStatus("接口请求失败");
                ysWithdrawalReceiptService.save(ysWithdrawalReceiptDO);
            }
        }catch (Exception e){
            log.error("调用银盛实时提现同步回执日志记录保存失败"+ysWithdrawalReceiptDO.toString());
        }


    }

    @Override
    public String withdrawalQuery(Map<String, Object> mapParams) {
        log.info("YsWithdrawalController ----------------withdrawalQuery"+JSON.toJSONString(mapParams));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String str = "";
        //获取银盛中心配置信息
        YsPayDTO ysPayDTO=ysBusinessPramService.ysBusinessPram();
        String bizContent = (String) mapParams.get("biz_content");
        //校验参数
        //Boolean bo = verifyWithdrawal(bizContent);
        //封装公共请求参数Map
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("method", "ysepay.merchant.withdraw.quick.query");
        paramMap.put("partner_id", ysPayDTO.getPARTNER_ID());
        paramMap.put("timestamp", DateFormatHelper.getNowTimeStr());
        paramMap.put("charset", ysPayDTO.getDEFAULT_CHARSET());
        paramMap.put("sign_type", ysPayDTO.getSIGN_ALGORITHM());
        paramMap.put("version", ysPayDTO.getVERSION());
        paramMap.put("biz_content", bizContent);

        //签名信息
        try {
            Map<String, String> sParaMap = ysBuildRequestParaService.buildRequestPara(paramMap);
            String returns = Https.httpsSend(ysPayDTO.getYSEPAY_GATEWAY_URL_DSF(), sParaMap);
            resultMap = (Map) JSON.parse(returns);
            Object obj = resultMap.get("ysepay_merchant_withdraw_quick_query_response");
            boolean verifyResult = false;
            if (obj != null) {
                int yscount = returns.toString().indexOf("ysepay_merchant_withdraw_quick_query_response");
                str = returns.substring(yscount);
                str = str.replace("ysepay_merchant_withdraw_quick_query_response", "");
                str = str.substring(2, str.length() - 1);
                verifyResult = ysVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), str, "utf-8");
                log.error("验证签名信息"+verifyResult);
                //map = JSONUtils.jsonToMap(str);
                log.error("银盛提现查询返回信息"+str);
                return str;
            }
        } catch (IOException e) {
            log.error("银盛提现查询接口"+e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e1) {
            log.error("银盛提现查询接口"+e1.getMessage());
            e1.printStackTrace();
        } finally {
            return str;
        }
    }

   /* //校验提现查询接口参数
    public Boolean verifyWithdrawal(Map<String, Object> paraMap) {

        String outTradeNo = (String) paraMap.get("out_trade_no");
        String shopdate = (String) paraMap.get("shopdate");

        if (paraMap.isEmpty()) {
            return false;
        }
        if (StringUtils.isEmpty(shopdate)) {
            log.error("YsWithdrawalServiceImpl-->verifyWithdrawal params 商户日期为" + shopdate);
            return false;
        }
        if (StringUtils.isEmpty(outTradeNo)) {
            log.error("YsWithdrawalServiceImpl-->verifyWithdrawal params 商户订单号为" + outTradeNo);
            return false;
        }
        return true;
    }*/
}
